/*******************************************************************************
 * Copyright 2008 www.softao.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.softao.ming.gwt.user.client;

import com.google.gwt.user.client.ui.Widget;

/**
 * 
 * @author Dop Sun Jul 14, 2008
 */
public class PatternRule implements ValidationRule {
	/** refer: http://regexlib.com/Search.aspx?k=email&c=-1&m=-1&ps=20 */
	public static final String EMAIL_PATTERN = "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$";

	/** refer: http://regexlib.com/Search.aspx?k=password&c=-1&m=-1&ps=20 */
	public static final String PASSWORD_PATTERN = "(?=^.{6,255}$)((?=.*\\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*";

	/**
	 * @return validation rule for email validation
	 */
	public static final PatternRule matchEmail() {
		return match(EMAIL_PATTERN);
	}

	/**
	 * @return validation rule for strong password
	 */
	public static final PatternRule matchPassword() {
		return match(PASSWORD_PATTERN);
	}

	/**
	 * @param pattern
	 * @return pattern rule
	 */
	public static final PatternRule match(String pattern) {
		return new PatternRule(pattern);
	}

	private String mPattern;

	/**
	 * Initializes a new instance of <code>PatternRule</code>.
	 * 
	 * @param pattern
	 */
	public PatternRule(String pattern) {
		if (pattern == null)
			throw new NullPointerException("pattern can not be null reference.");

		this.mPattern = pattern;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.softao.ming.gwt.user.client.ValidationRule#execute(com.google.gwt
	 * .user.client.ui.Widget)
	 */
	public boolean execute(Widget widget) {
		boolean result = false;
		if (this.mPattern == null) {
			result = true;
		} else {
			WidgetReaders.StringReader reader = WidgetReaders.getStringReader();
			String text = reader.read(widget);
			if (text != null) {
				result = text.matches(this.mPattern);
			}
		}
		return result;
	}

	/**
	 * @param pattern
	 *            the pattern to set
	 */
	public final void setPattern(String pattern) {
		mPattern = pattern;
	}

	/**
	 * @return the pattern
	 */
	public final String getPattern() {
		return mPattern;
	}

}
